package cn.bugstack.wrench.dynamic.config.center.listener;

import cn.bugstack.wrench.dynamic.config.center.model.valobj.AttributeVO;
import cn.bugstack.wrench.dynamic.config.center.service.IDynamicConfigCenterService;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * DynamicConfigCenterAdjustListener 实现了 Redisson 的 MessageListener<AttributeVO> 接口，
 * 能够自动订阅 Redis 的指定主题。当有配置变更消息发布到该主题时，监听器会被触发，进而完成属性的动态变更。
 * @author chenjia
 */
public class DynamicConfigCenterAdjustListener implements MessageListener<AttributeVO> {

    private final Logger log = LoggerFactory.getLogger(DynamicConfigCenterAdjustListener.class);

    private final IDynamicConfigCenterService dynamicConfigCenterService;

    public DynamicConfigCenterAdjustListener (IDynamicConfigCenterService dynamicConfigCenterService) {
        this.dynamicConfigCenterService = dynamicConfigCenterService;
    }

    /**
     * 这是消息监听的核心方法。当 Redis 发布订阅通道收到新的 AttributeVO 消息时，onMessage 会被自动调用。
     * @param charSequence charSequence
     * @param attributeVO  属性值调整值对象
     */
    @Override
    public void onMessage(CharSequence charSequence, AttributeVO attributeVO) {
        try {
            log.info("xfg-wrench dcc config attribute:{} value:{}", attributeVO.getAttribute(),attributeVO.getValue());
            dynamicConfigCenterService.adjustAttributeValue(attributeVO);
        }catch (Exception e){
            log.error("xfg-wrench dcc config attribute:{} value:{}", attributeVO.getAttribute(),attributeVO.getValue());
        }
    }
}
